package com.mujin.keji.collectionsystem.module.outboundtask.views;

import android.Manifest;
import android.arch.lifecycle.ViewModelProviders;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.mujin.keji.collectionsystem.CcsApplication;
import com.mujin.keji.collectionsystem.Constant;
import com.mujin.keji.collectionsystem.R;
import com.mujin.keji.collectionsystem.base.BaseActivity;
import com.mujin.keji.collectionsystem.dialog.BaseNiceDialog;
import com.mujin.keji.collectionsystem.dialog.NiceDialog;
import com.mujin.keji.collectionsystem.dialog.ViewConvertListener;
import com.mujin.keji.collectionsystem.dialog.ViewHolder;
import com.mujin.keji.collectionsystem.module.outboundtask.adapter.CaseInfoAdapter;
import com.mujin.keji.collectionsystem.module.outboundtask.dto.BoundTaskDto;
import com.mujin.keji.collectionsystem.module.outboundtask.dto.VisitCaseDto;
import com.mujin.keji.collectionsystem.module.outboundtask.viewmodel.BoundTaskListViewModel;
import com.mujin.keji.collectionsystem.module.outboundtask.vo.BeginVisitVo;
import com.mujin.keji.collectionsystem.permissions.PermissionUtils;
import com.mujin.keji.collectionsystem.permissions.PermissionsObserver;
import com.mujin.keji.collectionsystem.utils.DialogUtils;
import com.mujin.keji.collectionsystem.utils.EmptyUtils;
import com.mujin.keji.collectionsystem.utils.NumberUtils;
import com.mujin.keji.collectionsystem.utils.SPUtil;
import com.mujin.keji.collectionsystem.utils.ToastUtils;
import com.mujin.keji.collectionsystem.widget.CustomLazyViewPager;
import com.mujin.keji.collectionsystem.widget.NoPreloadViewPager;
import com.tbruyelle.rxpermissions.RxPermissions;

import java.util.ArrayList;
import java.util.List;

/**
 * 案件信息Activity界面
 *
 * @author weishixiong
 * @Time 2018-03-21
 */

public class CaseInformationActivity extends BaseActivity implements View.OnClickListener, NoPreloadViewPager.OnPageChangeListener,BDLocationListener {
    private List<Fragment> fragmentList;
    private CaseInfoAdapter caseInfoAdapter;
    private BoundTaskDto dto;
    private Button btnCase;
    private Button btnRemenber;
    private TextView tvTopName;
    private TextView tvTopStatus;
    private TextView tvTopAccount;
    private Button btnOk;
    VisitCaseDto visitCaseDto;
    private CustomLazyViewPager viewPager;
    public BoundTaskDto getDto() {
        return dto;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        CcsApplication.addActivity(this);

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        CcsApplication.getInstance().mLocationClient.stop();
        CcsApplication.getInstance().mLocationClient.unRegisterLocationListener(this);
        CcsApplication.removeActivity(this);
    }

    @Override
    protected void createViewModel() {
        boundTaskListViewModel = ViewModelProviders.of(this).get(BoundTaskListViewModel.class);
    }

    @Override
    public int intiLayout() {
        return R.layout.activity_caseinformation;
    }

    @Override
    public void initView() {
        setleftImage(R.drawable.image_arrow_left_white, true, null);
        viewPager = (CustomLazyViewPager) findViewById(R.id.viewPager);
        btnCase = (Button) findViewById(R.id.btn_case);
        btnRemenber = (Button) findViewById(R.id.btn_remenber);
        tvTopName = (TextView) findViewById(R.id.tv_top_name);
        tvTopStatus = (TextView) findViewById(R.id.tv_top_status);
        tvTopAccount = (TextView) findViewById(R.id.tv_top_account);
        btnOk = (Button) findViewById(R.id.btn_ok);
        viewPager.setScanScroll(false);
        initCaseInfoFragmentsView();
        initCase((VisitCaseDto) getIntent().getSerializableExtra("visitCaseDto"));
    }

    /**
     * 初始化案件信息两个状态的试图
     * 案件信息和催收记录
     */
    private void initCaseInfoFragmentsView() {
        fragmentList = new ArrayList<>();
        fragmentList.add(new CaseInfoFragment());
        fragmentList.add(new CollectionRecordsFragment());
        caseInfoAdapter = new CaseInfoAdapter(getSupportFragmentManager(), fragmentList);
        viewPager.setAdapter(caseInfoAdapter);

    }


    public void initCase(VisitCaseDto visitCaseDto) {
        if (EmptyUtils.isNotEmpty(visitCaseDto)) {
            this.dto = visitCaseDto.getDto();
            this.visitCaseDto = visitCaseDto;
            tvTopName.setText(dto.getVisitName());
            tvTopAccount.setText(NumberUtils.twoDecimalPlaces(dto.getLatestDebtMoney()));
            if (EmptyUtils.isNotEmpty(visitCaseDto.getDto().getStatus())) {
                if (visitCaseDto.getDto().getStatus() == 1) {
                    tvTopStatus.setText("待外访");
                    btnOk.setText("进入外访");
                    btnOk.setVisibility(View.VISIBLE);
                } else if (visitCaseDto.getDto().getStatus() == 2) {
                    btnOk.setText("外访详情");
                    btnOk.setVisibility(View.VISIBLE);
                    tvTopStatus.setText("已外访");
                } else if (visitCaseDto.getDto().getStatus() == 3) {
                    btnOk.setText("外访详情");
                    btnOk.setVisibility(View.VISIBLE);
                    tvTopStatus.setText("已完成");
                }
            }
        }

    }

    @Override
    public void initData() {

    }

    @Override
    protected void onStart() {
        super.onStart();
        initPermission();
    }

    /**
     * 获取定位权限
     */
    private void initPermission() {
        RxPermissions.getInstance(this).request(
                Manifest.permission.ACCESS_COARSE_LOCATION, //定位权限
                Manifest.permission.ACCESS_FINE_LOCATION//定位权限
        ).subscribe(new PermissionsObserver() {
            @Override
            protected void onGetPermissionsSuccess() {
                //开启定位
                CcsApplication.getInstance().mLocationClient.start();
                CcsApplication.getInstance().mLocationClient.registerLocationListener(CaseInformationActivity.this);
            }

            @Override
            protected void onGetPermissionsSuccessFailuer() {
                if (!PermissionUtils.hasPermission(CaseInformationActivity.this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION})) {
                    DialogUtils.showPerMissionDailog(Constant.FINALVALUE.LOCATION_MESSAGE, CaseInformationActivity.this);
                    return;
                }
                if (!PermissionUtils.hasPermission(CaseInformationActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION})) {
                    DialogUtils.showPerMissionDailog(Constant.FINALVALUE.LOCATION_MESSAGE, CaseInformationActivity.this);
                    return;
                }


            }
        });
    }
    @Override
    public void initListener() {
        viewPager.setOnPageChangeListener(this);
        btnCase.setOnClickListener(this);
        btnRemenber.setOnClickListener(this);
        btnOk.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_ok:
                //
                if (!EmptyUtils.isNotEmpty(visitCaseDto) || !EmptyUtils.isNotEmpty(visitCaseDto.getDto())) {
                    ToastUtils.showToast("系统异常,请稍后再试");
                    return;
                }
                showTips(visitCaseDto.getDto());
                break;
            case R.id.btn_case:
                btnCase.setBackgroundResource(R.drawable.shape_file_select_bg);
                btnRemenber.setBackgroundResource(R.drawable.shape_file_normal_bg);
                btnCase.setTextColor(getResources().getColor(R.color.color_main_title));
                btnRemenber.setTextColor(getResources().getColor(R.color.color_white));
                viewPager.setCurrentItem(0);
                break;
            case R.id.btn_remenber:
                btnCase.setBackgroundResource(R.drawable.shape_file_normal_bg);
                btnRemenber.setBackgroundResource(R.drawable.shape_file_select_bg);
                btnCase.setTextColor(getResources().getColor(R.color.color_white));
                btnRemenber.setTextColor(getResources().getColor(R.color.color_main_title));
                viewPager.setCurrentItem(1);
                break;
        }
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {

    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    private BoundTaskListViewModel boundTaskListViewModel;

    /**
     * 提示是否开始外访
     *
     * @param boundTaskDto
     */
    private void showTips(final BoundTaskDto boundTaskDto) {
        // 判断是的要提示对话框 true 是
        if (SPUtil.getData(Constant.SP.SHOW_TIP_SP, Constant.SP.SHOW_TIP, Boolean.class, true) && boundTaskDto.getStatus() == 1) {
            BeginVisitVo visitVo = new BeginVisitVo();
            visitVo.setApplyId(boundTaskDto.getId());
            visitVo.setIsBegin(0);
           // getLoadingDialog().showDialog();
            //查询接口 时间是否被初始化 判断 是否外访 是否提示对话框

            //start visit 开始外访 初始化外访时间 和地址
            startToVist(boundTaskDto);

//            boundTaskListViewModel.beginVisit(visitVo).observe(this, new Observer<BaseDto<String>>() {
//                @Override
//                public void onChanged(@Nullable BaseDto<String> stringBaseDto) {
//                    getLoadingDialog().dismiss();
//                    //没有时间 弹出对话框
//                    if (stringBaseDto.getCode() == Constant.Server.SUCCESS_CODE) {
//                        //时间是空的 未开启外访 需要提示对话框
//                        if (TextUtils.isEmpty(stringBaseDto.getData())) {
//                            showTipsDialog(boundTaskDto);
//                        }
//                        //时间不是空的 直接去外访
//                        else {
//                            //start visit 开始外访 初始化外访时间 和地址
//                            startToVist(boundTaskDto);
//                        }
//
//                    } else {
//                        ToastUtils.showToast(stringBaseDto.getMsg());
//                    }
//                }
//            });
        }
        //不用提示 则 直接去外访 初始化 外访时间 和地址
        else {
            //start visit 开始外访 初始化外访时间 和地址
            startToVist(boundTaskDto);
        }


    }
    private boolean isSelectedTip;
    /**
     * 弹出提示对话框
     * @param boundTaskDto
     */
    private void showTipsDialog(final BoundTaskDto boundTaskDto) {
        NiceDialog.init()
                .setLayoutId(R.layout.dialog_visit_tip)
                .setConvertListener(new ViewConvertListener() {
                    @Override
                    public void convertView(ViewHolder holder, final BaseNiceDialog dialog) {
                        dialog.setOutCancel(false);
                        final RelativeLayout rlGoYes = (RelativeLayout) holder.getView(R.id.rl_go_yes);
                        //  final ImageView ivGoYes = (ImageView) holder.getView(R.id.iv_go_yes);
                        TextView tvNo = (TextView) holder.getView(R.id.tv_no);
                        TextView tvOk = (TextView) holder.getView(R.id.tv_ok);
                        rlGoYes.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                if(isSelectedTip){
                                    rlGoYes.setBackgroundResource(R.drawable.image_select_no);
                                }
                                else{
                                    rlGoYes.setBackgroundResource(R.drawable.image_select_yes);
                                }
                                isSelectedTip = !isSelectedTip;
                            }
                        });
                        tvOk.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                dialog.dismiss();
                                //选中
                                if (isSelectedTip) {
                                    SPUtil.putData(Constant.SP.SHOW_TIP_SP, Constant.SP.SHOW_TIP, false);
                                } else {
                                    SPUtil.putData(Constant.SP.SHOW_TIP_SP, Constant.SP.SHOW_TIP, true);
                                }
                                //start visit 开始外访 初始化外访时间 和地址
                                startToVist(boundTaskDto);
                            }
                        });
                        tvNo.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                //选中
                                if (isSelectedTip) {
                                    SPUtil.putData(Constant.SP.SHOW_TIP_SP, Constant.SP.SHOW_TIP, false);
                                } else {
                                    SPUtil.putData(Constant.SP.SHOW_TIP_SP, Constant.SP.SHOW_TIP, true);
                                }
                                dialog.dismiss();
                            }
                        });
                    }
                })

                .show(getSupportFragmentManager());
    }

    /**
     * 开始外访
     *
     * @param boundTaskDto
     */
    private void startToVist(final BoundTaskDto boundTaskDto) {
        if (1 == boundTaskDto.getStatus()) {
           // getLoadingDialog().showDialog();
            BeginVisitVo visitVo = new BeginVisitVo();
            visitVo.setApplyId(boundTaskDto.getId());
            visitVo.setIsBegin(1);
//            if(TextUtils.isEmpty(currentAdress)){
//                ToastUtils.showToast("未获取到当前定位地址，请检查手机定位权限是否开启");
//                return;
//            }
            visitVo.setLocation(currentAdress);
            toVisitDetail();
//            boundTaskListViewModel.beginVisit(visitVo).observe(this, new Observer<BaseDto<String>>() {
//                @Override
//                public void onChanged(@Nullable BaseDto<String> stringBaseDto) {
//                    getLoadingDialog().dismiss();
//                    if (stringBaseDto.getCode() == Constant.Server.SUCCESS_CODE) {
//                        toVisitDetail();
//                    } else {
//                        ToastUtils.showToast(stringBaseDto.getMsg());
//                    }
//
//                }
//            });
        } else {
            toVisitDetail();
        }

    }

    /**
     * 进入外访界面
     *
     * @param
     */
    private void toVisitDetail() {
        Intent intent = new Intent(CaseInformationActivity.this, BoundDetailActivity.class);
        intent.putExtra("visitCaseDto", visitCaseDto);
        intent.putExtra("isTrip",getIntent().getBooleanExtra("isTrip",false));
        startActivity(intent);
    }

    private String currentAdress;
    @Override
    public void onReceiveLocation(BDLocation bdLocation) {
        if(bdLocation!=null){
            currentAdress = bdLocation.getAddrStr();
        }

    }
}
